package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JwtUtils;
import com.leyou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 用户登录授权中心
     * @param username
     * @param password
     * @return
     */
    public String accredit(String username, String password) {
        //查询用户是否存在
        User user = userClient.queryUser(username, password);
        if(user==null){
            return null;
        }
        try {
            //生成token
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());
            userInfo.setUsername(user.getUsername());
            return JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
        }catch (Exception e){
            e.printStackTrace();
        }
        //出现异常返回
        return null;
    }
    /**
     * 获取用户信息，用来登录后展示
     * @param token
     * @return
     */
    public UserInfo verify(String token) {
        try {
            //通过公钥解码token得到userInfo对象
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            return userInfo;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
